package com.itouch.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EncodingUtils;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

/**
 * 
* @Title: CommonMethodTools.java 
* @Package cn.com.itouch.ydzf.tools 
* @Description: TODO(常用静态方法) 
* @author sunshineHu(hucx@itouch.com.cn)  
* @date 2014年4月9日 上午10:39:23 
* @version V1.0
 */
public class CommonMethodTools {

	public static String getMyUUID(Context c){
		 
		  final TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);   
		 
		  final String tmDevice, tmSerial, androidId;   
		 
		  tmDevice = "" + tm.getDeviceId();  
		 
		  tmSerial = "" + tm.getSimSerialNumber();   
		 
		  androidId = "" + android.provider.Settings.Secure.getString(c.getContentResolver(),android.provider.Settings.Secure.ANDROID_ID);   
		 
		  UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());   
		 
		  String uniqueId = deviceUuid.toString();
		 
		  Log.d("debug","uuid="+uniqueId);
		 
		  return uniqueId;
		 
		 }

	
	
	
	public static void showToast(final String text,final Context c){
		
		new Thread(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				Looper.prepare();
				Toast.makeText(c, text, Toast.LENGTH_SHORT).show();
				Looper.loop(); 
			}
		}.start();
		
	}
	
	
	public static void exitApp(Context c){
		
		//广播关闭activity
		Intent intent = new Intent();  
        intent.setAction("ExitApp");  
        c.sendBroadcast(intent);
        new Thread(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				try {
					sleep(800);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.exit(0);
			}
        	
        }.start();
        
	}
	
	
	
	public static Bitmap getimage(String srcPath) { 
        BitmapFactory.Options newOpts = new BitmapFactory.Options(); 
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了 
        newOpts.inJustDecodeBounds = true; 
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空 
        newOpts.inJustDecodeBounds = false; 
        int w = newOpts.outWidth; 
        int h = newOpts.outHeight; 
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为 
        float hh = 100f;//这里设置高度为800f 
        float ww = 100f;//这里设置宽度为480f 
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可 
        int be = 1;//be=1表示不缩放 
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放 
            be = (int) (newOpts.outWidth / ww); 
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放 
            be = (int) (newOpts.outHeight / hh); 
        } 
        if (be <= 0) 
            be = 1; 
        newOpts.inSampleSize = be;//设置缩放比例 
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了 
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts); 
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩 
    }
	
	
	
	public static boolean getImageByScale(String srcPath,float width,String targetPath) { 
        BitmapFactory.Options newOpts = new BitmapFactory.Options(); 
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了 
        newOpts.inJustDecodeBounds = true; 
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空 
        newOpts.inJustDecodeBounds = false; 
        int w = newOpts.outWidth; 
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为 
        float ww = width;//这里设置宽度为480f 
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可 
        int be = 1;//be=1表示不缩放 
        if (w > ww) {//如果宽度大的话根据宽度固定大小缩放 
            be = (int) (newOpts.outWidth / ww); 
        } 
        if (be <= 0) 
            be = 1; 
        newOpts.inSampleSize = be;//设置缩放比例 
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了 
        bitmap =  compressImage(BitmapFactory.decodeFile(srcPath, newOpts)); 

        CompressFormat format= Bitmap.CompressFormat.JPEG;  
        int quality = 80;  
        OutputStream stream = null;  
        try {  
                stream = new FileOutputStream(targetPath);  
        } catch (FileNotFoundException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
        }  
  
        return bitmap.compress(format, quality, stream);  
        
    }

	
	
	public static Bitmap comp(Bitmap image) {  
	      
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();         
	    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
	    if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出    
	        baos.reset();//重置baos即清空baos  
	        image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%，把压缩后的数据存放到baos中  
	    }  
	    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());  
	    BitmapFactory.Options newOpts = new BitmapFactory.Options();  
	    //开始读入图片，此时把options.inJustDecodeBounds 设回true了  
	    newOpts.inJustDecodeBounds = true;  
	    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);  
	    newOpts.inJustDecodeBounds = false;  
	    int w = newOpts.outWidth;  
	    int h = newOpts.outHeight;  
	    //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为  
	    float hh = 800f;//这里设置高度为800f  
	    float ww = 480f;//这里设置宽度为480f  
	    //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可  
	    int be = 1;//be=1表示不缩放  
	    if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放  
	        be = (int) (newOpts.outWidth / ww);  
	    } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放  
	        be = (int) (newOpts.outHeight / hh);  
	    }  
	    if (be <= 0)  
	        be = 1;  
	    newOpts.inSampleSize = be;//设置缩放比例  
	    //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了  
	    isBm = new ByteArrayInputStream(baos.toByteArray());  
	    bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);  
	    return compressImage(bitmap);//压缩好比例大小后再进行质量压缩  
	}  
	
	
	private static Bitmap compressImage(Bitmap image) { 
		   
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中 
        int options = 100; 
        while ( baos.toByteArray().length / 1024>100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩        
            baos.reset();//重置baos即清空baos 
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中 
            options -= 10;//每次都减少10 
        } 
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中 
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片 
        return bitmap; 
	    }

	
	 public static File getFileFromBytes(byte[] b, String outputFile) {
	      BufferedOutputStream stream = null;
	       File file = null;
	       try {
	      file = new File(outputFile);
	           FileOutputStream fstream = new FileOutputStream(file);
	           stream = new BufferedOutputStream(fstream);
	           stream.write(b);
	       } catch (Exception e) {
	           e.printStackTrace();
	      } finally {
	          if (stream != null) {
	               try {
	                  stream.close();
	               } catch (IOException e1) {
	                  e1.printStackTrace();
	              }
	          }
	      }
	       return file;
	   }
	 
	 
	 
	 
	 /**
		 * 从asserts获取文件
		 * @param fileName
		 * @return
		 */
		 public static String getFromAssets(String fileName,Context c){ 
			  String result = "";
			   try {
			InputStream in = c.getResources().getAssets().open(fileName);
			//获取文件的字节数
			int lenght = in.available();
			//创建byte数组
			byte[]  buffer = new byte[lenght];
			//将文件中的数据读到byte数组中
			in.read(buffer);
			result = EncodingUtils.getString(buffer, "UTF-8");
			} catch (Exception e) {
			e.printStackTrace();
			}
			return result;
			}
	 
		 
		 
		 

	//删除通知   


	 public static void clearNotification(int id,Context c){

        // 启动后删除之前我们定义的通知  


        NotificationManager notificationManager = (NotificationManager) c

                .getSystemService(Context.NOTIFICATION_SERVICE);  

        notificationManager.cancel(id); 

	    }

			 
			 
		public static float getScreenDensity(Context context) {
			return context.getResources().getDisplayMetrics().density;
		}

		public static int dip2px(Context context, float px) {
			final float scale = getScreenDensity(context);
			return (int) (px * scale + 0.5);
		}
		
		
		

		/**
		 * Hcx
		 * @param fileName
		 * @param actionUrl
		 * @return
		 */
		public static String uploadFile(File file,String actionUrl){
			try {
				HttpClient httpclient= new DefaultHttpClient();
			     HttpPost httpPost= new HttpPost(actionUrl);
			      MultipartEntity mulentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			      FileBody filebody = new FileBody(file);
			      mulentity.addPart("image",filebody );  
			      httpPost.setEntity(mulentity);
			      HttpResponse response =    httpclient.execute(httpPost);

				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
						String ss=retrieveInputStream(response.getEntity());
						//String code   = (String)  jsonObject3.get(PublicTools.KEY_COLUMN_CODE);
						//String msg    = (String)  jsonObject3.get("path");
						return ss;
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		
		
		protected static String retrieveInputStream(HttpEntity httpEntity) {
			Long length1 = httpEntity.getContentLength();
			int length = (int) httpEntity.getContentLength();
			if (length < 0){
				length = 10000;
			}
			if(length == 0){
				length = 10000;
			}
			StringBuffer stringBuffer = new StringBuffer(length);
			try {
				InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
				char buffer[] = new char[length];
				int count;
				while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
					stringBuffer.append(buffer, 0, count);
				}
			}catch(IOException e){
				e.printStackTrace();
			}
			return stringBuffer.toString();
		}	
		
}
